/**
 * Created by tz on 2018/12/27.
 */
import React, { Component } from 'react';
import {Form, Card, Button, Row, Col, Table, Upload, Icon, Popconfirm, Input, Select, Checkbox} from 'antd';
import NewsService from '../../service/NewsService';
import { message } from 'antd';

const uploadButton = (
    <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传照片</div>
    </div>
);
const Option = Select.Option;

export default class NewsEdit extends Component {

    state = {
        title:'News新增',
        data:{},
        formItems: [
            {name: '标题', type: 'input', fieldName: 'title'},
            {name: '图片1', type: 'img', fieldName: 'pic1'},
            {name: '图片2', type: 'img', fieldName: 'pic2'},
            {name: '图片3', type: 'img', fieldName: 'pic3'},
            {name: '类型', type: 'select', fieldName: 'type'},
            {name: '链接路径', type: 'input', fieldName: 'source'},
            {name: '链接分享路径', type: 'input', fieldName: 'shareUrl'},
            {name: '是否置顶', type: 'choice', fieldName: 'topmost'},
        ],
        loading:false,
        error:false,
        selData:{type:[['TEXT','文本'],['NEWS','单图'],['THREEIMAGES','三图']]},
        fileListObj:{pic1:[],pic2:[],pic3:[]}

    };

    constructor(props) {
        super(props)
    }

    componentDidMount() {
        let id = this.props.match.params.id;
        if(id){
            this.setState({title:'News修改'});
            this.fetch(id);
        }
    }

    fetch(id){
        this.setState({
            loading: true
        });
        NewsService.getOne(id).done((res)=>{
            console.log(res.entity);
            this.state.data = res.entity;
            Object.keys(this.state.fileListObj).forEach((item,i)=>{
                if(this.state.data[item]){
                    this.state.fileListObj[item].push({uid:i,url:this.state.data[item]});
                }
            });
            this.setState({loading: false})
        })
    }

    handleChange(item,fileObj){
        let info = fileObj.file;
        let fileList = fileObj.fileList;
        //选择文件并上传
        console.log('info',info);
        if(info.status==='done'){
            this.state.data[item.fieldName]=info.response;
        }else if(info.status==='removed'){
            this.state.data[item.fieldName] = undefined;
        }
        this.state.fileListObj[item.fieldName] = fileList;
        console.log(this.state.data);
        this.forceUpdate();
    }

    //页面check
    check(){
        console.log('this.state.data',this.state.data);
        this.state.error = false;

        //标题check
        if (this.state.data.title === null || this.state.data.title === '' || typeof this.state.data.title === 'undefined') {
            this.state.error = true;
            message.error("请输入标题！");
            return
        }
        if (this.state.data.title.length > 255) {
            this.state.error = true;
            message.error("标题最多只能输入255个文字！");
            return
        }


        //类型check
        if (this.state.data.type === null || this.state.data.type === '' || typeof this.state.data.type === 'undefined') {
            this.state.error = true;
            message.error("请选择类型！");
            return
        }

        //图片check
        if (this.state.data.type === "NEWS") {
            if (this.state.data.pic1 === null || this.state.data.pic1 === '' || typeof this.state.data.pic1 === 'undefined') {
                this.state.error = true;
                message.error("请选择图片1！");
                return
            }
        } else if (this.state.data.type === "THREEIMAGES") {
            if (this.state.data.pic1 === null || this.state.data.pic1 === '' || typeof this.state.data.pic1 === 'undefined') {
                this.state.error = true;
                message.error("请选择图片1！");
                return
            }
            if (this.state.data.pic2 === null || this.state.data.pic2 === '' || typeof this.state.data.pic2 === 'undefined') {
                this.state.error = true;
                message.error("请选择图片2！");
                return
            }
            if (this.state.data.pic3 === null || this.state.data.pic3 === '' || typeof this.state.data.pic3 === 'undefined') {
                this.state.error = true;
                message.error("请选择图片3！");
                return
            }
        }

        //链接路径check
        if (this.state.data.source === null || this.state.data.source === '' || typeof this.state.data.source === 'undefined') {
            this.state.error = true;
            message.error("请输入链接路径！");
            return
        }
        if (this.state.data.source.length > 255) {
            this.state.error = true;
            message.error("链接路径最多只能输入255个文字！");
            return
        }

        //链接分享路径check
        if (this.state.data.shareUrl === null || this.state.data.shareUrl === '' || typeof this.state.data.shareUrl === 'undefined') {
            this.state.error = true;
            message.error("请输入链接分享路径！");
            return
        }
        if (this.state.data.shareUrl.length > 255) {
            this.state.error = true;
            message.error("链接分享路径最多只能输入255个文字！");
            return
        }
    }

    save(){
        console.log(this.state.data);

        //页面check
        this.check();

        if (this.state.error === false) {
            let id = this.props.match.params.id;
            if(id){
                NewsService.updateOne(this.state.data).done((res)=>{
                    console.log(res);
                    this.props.history.goBack();
                })
            }else{
                NewsService.addOne(this.state.data).done((res)=>{
                    console.log(res);
                    this.props.history.goBack();
                })
            }
        }
    }

    //页面渲染
    render() {
        return (
            <Card title={this.state.title}>
                <Form>
                    {this.state.formItems.map((item,i)=>{
                        if(item.type==='input'){
                            return(
                                <Form.Item
                                    label={item.name}
                                    key={i}
                                >
                                    <Input placeholder={"请输入"+item.name}
                                           value={this.state.data[item.fieldName]}
                                           onChange={(e)=>{
                                        this.state.data[item.fieldName] = e.target.value;
                                        this.forceUpdate();
                                    }}/>
                                </Form.Item>
                            )
                        }else if(item.type==='img'){
                            return(
                                <Form.Item
                                    label={item.name}
                                    key={i}
                                >
                                    <Upload
                                        key={"upload"+i}
                                        action='/api/upload?path=news'
                                        accept='.jpg,.jpeg,.png'
                                        listType='picture-card'
                                        fileList={this.state.fileListObj[item.fieldName]}
                                        //beforeUpload={this.beforeUpload}
                                        //onPreview={this.handlePreview.bind(this)}
                                        headers={{Authorization:('Bearer '+window.sessionStorage.getItem('token'))}}
                                        onChange={this.handleChange.bind(this,item)}
                                    >
                                        {this.state.fileListObj[item.fieldName].length >= 1 ? null : uploadButton}
                                    </Upload>
                                </Form.Item>
                            )
                        }else if(item.type==='select'){
                            return(
                                <Form.Item
                                    label={item.name}
                                    key={i}
                                >
                                    <Select placeholder={"请选择" + item.name}
                                            value={this.state.data[item.fieldName]}
                                            onChange={(e)=>{
                                                this.state.data[item.fieldName] = e;
                                                this.forceUpdate();
                                            }}
                                    >
                                        {this.state.selData[item.fieldName].map((item1, j) => {
                                            return (
                                                <Option key={'o_' + j} value={item1[0]}>{item1[1]}</Option>
                                            )
                                        })}
                                    </Select>
                                </Form.Item>
                            )
                        }else if(item.type==='choice'){
                            return(
                                <Form.Item
                                    label={item.name}
                                    key={i}
                                >
                                    <Checkbox checked={this.state.data[item.fieldName]} onChange={(e)=>{
                                        this.state.data[item.fieldName] = e.target.checked;
                                        this.forceUpdate();
                                    }}/>
                                </Form.Item>
                            )
                        }
                    })}
                    <Form.Item>
                        <Popconfirm placement="top" okText="确认" cancelText="关闭" title="是否确定保存?" onConfirm={() =>{
                            this.save();
                        }}>
                            <Button type="primary" icon="save">保存</Button>
                        </Popconfirm>

                    </Form.Item>
                </Form>
            </Card>
        );
    }
}